<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PhoneCode extends Model
{
    protected $table='phone_codes';
    protected $fillable=[
        'phone','type','code','use_at','overdue_at'
    ];

    /**
     * 添加新的验证码
     * @param $data
     * @return mixed
     */
    static public function add($data)
    {
        //删除以前的验证码，避免数据量太大
        self::where(['phone'=>$data['phone'],'type'=>$data['type']])->delete();
        $re  = self::create($data);

        return $re;
    }

    /**
     * 验证码比较
     * @param $phone
     * @param $code
     * @$type $code
     * @return mixed
     */
    static public  function  validation($phone,$code,$type)
    {

        //当前日期
        $now = date('Y-m-d H:i:s');
        $re =  self::where(['phone'=>$phone,'type'=>$type,'code'=>$code])->whereNull('use_at')->where('overdue_at','>=',$now)->orderBy('id','desc')->first();
        if($re){
            //修改使用日期
            $re->use_at = $now;
            $re->save();
        }
        return $re;
    }
}
